#include "tablewidgetsdelegate.h"

#include <QComboBox>
#include <QSerialPortInfo>
#include <QSpinBox>

twSerialDelegate::twSerialDelegate(ESerialType itemtype,QObject *parent)
{
    this->itemType=itemtype;
}

twSerialDelegate::twSerialDelegate(twSerialDelegate::ESerialType itemtype, QStringList ports, QObject *parent)
{
    this->serials=ports;
    this->itemType=itemtype;
}

void twSerialDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyledItemDelegate::paint(painter, option, index);
}

QWidget *twSerialDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStringList ql_baud,ql_parity,ql_data,ql_stop;
    QComboBox *cb=new QComboBox(parent);
    ql_baud<<"2400"<<"4800"<<"9600"<<"19200"<<"38400"<<"115200";
    ql_parity<<"N"<<"O"<<"E";
    ql_data<<"8"<<"9";
    ql_stop<<"1"<<"2";
    switch(this->itemType)
    {
    case serialname:
    {
//        foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
//        {
//            cb->addItem(info.portName());
//        }
        cb->addItems(this->serials);
        break;
    }
    case serialbaud:
    {
        cb->addItems(ql_baud);
        break;
    }
    case serialparity:
    {
        cb->addItems(ql_parity);
        break;
    }
    case serialdata:
    {
        cb->addItems(ql_data);
        break;
    }
    case serialstop:
    {
        cb->addItems(ql_stop);
        break;
    }
    }
    return cb;
}

void twSerialDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    int strindex=-1;
    QComboBox *cb=qobject_cast<QComboBox *>(editor);
    strindex=cb->findText(index.model()->data(index,Qt::DisplayRole).toString());
    cb->setCurrentIndex(strindex);
}

void twSerialDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox *cb=qobject_cast<QComboBox *>(editor);
    model->setData(index, cb->currentText());
}



twNumberDelegate::twNumberDelegate(QObject *parent)
{

}

void twNumberDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyledItemDelegate::paint(painter, option, index);
}

QWidget *twNumberDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QSpinBox *sb=new QSpinBox(parent);
    sb->setMaximum(600);
    return sb;
}

void twNumberDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QSpinBox *sb=qobject_cast<QSpinBox *>(editor);
    sb->setValue(index.model()->data(index,Qt::DisplayRole).toInt());
}

void twNumberDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QSpinBox *sb=qobject_cast<QSpinBox *>(editor);
    model->setData(index,sb->value());
}
